﻿
using GetData.webProductClass;
using jutehui.GetData;
using jutehui.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace GetData
{
    public class czfxh
    {
        /// <summary>
        /// 超值分享汇 HTML信息 获取商品信息 并保存到数据库
        /// </summary>
        /// <returns></returns>
        public string GetSaleURL(string url, int navType)
        {
            var htmlText = CustomMethod.GetHtmlByHttpHelper(url);
            var productList = GetProductByRegexToHtml(htmlText, navType);
            if (productList == null || productList.Count < 1)
            {
                return "网络异常，未能获取数据";
            }
            // GetProductList(jsonStr, productList);//得到要插入数据库的数据
            //保存数据库
            DataTable dt = null;
            //转化成table插入
            string errorMsg = "";
            dt = CustomMethod.ListToDataTable<Product>(productList, "Product", ref errorMsg);
            if (dt == null || dt.Rows.Count < 1)
            {
                return errorMsg;
            }
            jutehui.BLL.Product bll = new jutehui.BLL.Product();
            string msg = "";

            if (bll.SaveTableData("Product", dt, out msg))
            {
                return "";
            }
            else //返回失败信息
            {
                return msg;
            }
        }
        /// <summary>
        /// 根据正则解析商品信息
        /// </summary>
        /// <param name="htmlText"></param>
        /// <param name="type">海购还是精选</param>
        /// <returns></returns>
        private List<Product> GetProductByRegexToHtml(string htmlText, int type)
        {
            List<Product> pList = new List<Product>();
            
            string productRegex = @"<div class=""post"" id=""post-(.*?)>[\s\S]*?<div class=""under"">";
            productRegex = @"id=""post-(.*?)>[\s\S]*?<div class=""post""";
            var list = CustomMethod.GetInfoByRegex(productRegex, htmlText, 0);
            if (list == null || list.Count < 1)
            {
                string msg = "超值分享汇：GetProductByRegex ，没有抓到匹配的商品，检查匹配规则。";
                CustomMethod.WriteLog(msg);
                return null;
            }
            ProductTypeEnum pEnum = new ProductTypeEnum();
            //每个商品匹配所有相关属性并赋值
            for (int index = 0; index < list.Count; index++)
            {
                Product product = new Product();
                product.FromWeb = "超值分享汇";
                product.TypeId = type;
                try
                {
                    var herfList = CustomMethod.GetInfoFroma(list[index]);
                    if (herfList == null || herfList.Count < 2)
                    {
                        CustomMethod.WriteLog("超值分享汇：没有获取到herf连接数据");
                        continue;
                    }
                    product.Pname = herfList[1];
                    //购买链接
                    string buyRegex = @"<div class=""buy_url"">[\s\S]*?</div>";
                    var buyContent = CustomMethod.GetInfoByRegex(buyRegex, list[index], 0);
                    if (buyContent == null || buyContent.Count < 1)
                    {
                       if (index == 0)//第一次就出现匹配不到的情况 记录 可能出现规则变动
                        {
                            CustomMethod.WriteLog("超值分享汇：没有获取到商品购买链接区域内容");
                        }
                        continue;
                    }
                    string buyCont = Regex.Replace(buyContent[0], @"\s+", "");
                    var buyList = CustomMethod.GetInfoFroma(buyCont);
                    if (buyList == null || buyList.Count < 1)
                    {
                        CustomMethod.WriteLog("超值分享汇：没有获取到商品购买链接");
                        continue;
                    }
                    string productUrl = "";
                    product.Plink = MallsEnumClass.GetSourceUrl(buyList[0], ref productUrl);// Enum(buyList[0], ref productUrl);
                    if (product.Plink == "")
                    {
                        // CustomMethod.WriteLog("超值分享汇：没有获取到商品购买链接");
                        if (productUrl == "")
                        {
                            CustomMethod.WriteLog("超值分享汇：没有获取到商品购买链接");
                        }
                        continue;
                    }
                    product.Memo = productUrl;
                    //描述
                    string desRegex = @"<div class=""conBox excerptBox"" id=(.*?)>[\s\S]*?</div>";
                    var desList = CustomMethod.GetInfoByRegex(desRegex, list[index], 0);
                    if (desList == null || desList.Count < 1)
                    {
                        product.Description = product.Pname;
                    }
                    //-----------------------------------获取商品分类-------------------------------------
                    string regex = @"<div class=""under"">[\s\S]*?</div>";
                    product.ProductTypeId = pEnum.GetProductTypeId(list[index], regex, typeof(ProductTypeEnum.cxfxhType),0); 
                    //------------------------------------------------------------------------------------
                    //获取source
                    var sourList = CustomMethod.GetInfoFroma(desList[0]);
                    if (sourList != null && sourList.Count > 0)
                    {
                        product.Source = sourList[1];
                    }
                    else
                    {
                        //CustomMethod.WriteLog("超值分享汇：没有获取到商品来源");
                        product.Source = "";
                    }

                    ////获取描述信息
                    //string pRegex = @"<p itemprop=""description"">[\s\S]*?</p>";
                    //var despList = CustomMethod.GetInfoByRegex(pRegex, desList[0], 0);
                    //string description = "";
                    //for (int count = 0; count < desList.Count; count++)
                    //{
                    //    description += Regex.Replace(desList[count], @"<(.[^>]*)>", "") + "|||";

                    //}
                    //product.Description = description == "" ? product.Pname : description;
                    if (product.Description.Contains("海淘") || product.Description.Contains("到手约"))
                    {
                        product.TypeId = (int)MallsEnumClass.NavigationType.海淘;
                    }
                    product.Price = "";

                    string imgUrl = CustomMethod.GetImgUrl(list[index], "超值分享汇");
                    if (imgUrl != "")
                    { 
                        //base64编码文件  解码成图片文件保存到服务器为客户端提供请求
                        if (imgUrl.Contains("base64"))
                        {
                            string picName = imgUrl.Substring(imgUrl.Length - 10, 10).Replace("/", "");
                            int startIndex = imgUrl.IndexOf("base64,");
                            string picstr = imgUrl.Substring(startIndex + 7, imgUrl.Length - 7 - startIndex);
                            string picPath = Base64StringToImage(picstr, picName);
                            if (picPath == "")
                            {
                                CustomMethod.WriteLog("超值分享汇，没有获取到图片信息");
                                // continue;
                            }
                            product.ImgUrl = picPath;
                        }
                        else
                        {
                            product.ImgUrl = imgUrl;
                        }
                    }

                }
                catch (Exception ex)
                {
                    string msg = "超值分享汇：GetProductByRegex ，" + ex.Message.ToString();
                    CustomMethod.WriteLog(msg + index);
                }
                product.UpdateTime = DateTime.Now;
                product.UpdateTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                product.Pname = System.Web.HttpUtility.HtmlEncode(product.Pname);
                
                pList.Add(product);
            } 
          var newList =CustomMethod.GetDistinctProdcuts(pList);
          newList.Reverse();
          return newList;
        }

        //base64编码的文本 转为    图片
        private string Base64StringToImage(string txtFileName, string picName)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(txtFileName);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                string name = DateTime.Now.ToString("yyyyMMddHH") + picName + ".jpeg";
                if (!Directory.Exists(@"D:/wwwroot/1jutehui/productImgs"))
                {
                    Directory.CreateDirectory(@"D:/wwwroot/1jutehui/productImgs");
                }

                bmp.Save(@"D:\wwwroot\1jutehui\productImgs\" + name, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Close();
                bmp.Dispose();
                string path = "http://jth.lerdian.cn/productImgs/" + name;
                return path;
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Base64StringToImage 转换失败\nException：" + ex.Message);
                CustomMethod.WriteLog("Base64StringToImage 转换失败\nException：" + ex.Message);
                return "";
            }
        }
    }
}
